




class AudioRecorder {
    constructor() {
        this.mediaRecorder = null;
        this.audioChunks = [];
        this.isRecording = false;
        this.stream = null;
    }




    async init() {
        try {

            this.stream = await navigator.mediaDevices.getUserMedia({
                audio: {
                    echoCancellation: true,
                    noiseSuppression: true,
                    autoGainControl: true
                }
            });


            this.mediaRecorder = new MediaRecorder(this.stream, {
                mimeType: 'audio/webm'
            });


            this.mediaRecorder.ondataavailable = (event) => {
                if (event.data.size > 0) {
                    this.audioChunks.push(event.data);
                }
            };


            this.mediaRecorder.onstop = () => {
                this.isRecording = false;
            };

            console.log('✓ 录音器初始化成功');
            return true;
        } catch (error) {
            console.error('❌ 录音器初始化失败:', error);
            if (error.name === 'NotAllowedError') {
                alert('请允许访问麦克风以使用录音功能');
            } else if (error.name === 'NotFoundError') {
                alert('未检测到麦克风设备');
            } else {
                alert('录音器初始化失败: ' + error.message);
            }
            return false;
        }
    }




    async start() {
        if (this.isRecording) {
            console.warn('⚠️  正在录音中');
            return false;
        }


        if (!this.mediaRecorder) {
            const success = await this.init();
            if (!success) return false;
        }


        this.audioChunks = [];


        this.mediaRecorder.start();
        this.isRecording = true;

        console.log('🎤 开始录音');
        return true;
    }





    stop() {
        return new Promise((resolve, reject) => {
            if (!this.isRecording) {
                reject(new Error('未在录音中'));
                return;
            }


            this.mediaRecorder.onstop = () => {
                this.isRecording = false;


                const audioBlob = new Blob(this.audioChunks, {
                    type: 'audio/webm'
                });

                console.log('🛑 停止录音');
                console.log(`   大小: ${(audioBlob.size / 1024).toFixed(2)} KB`);

                resolve(audioBlob);
            };


            this.mediaRecorder.stop();
        });
    }




    release() {
        if (this.stream) {
            this.stream.getTracks().forEach(track => track.stop());
            this.stream = null;
        }
        this.mediaRecorder = null;
        this.audioChunks = [];
        this.isRecording = false;

        console.log('🔧 录音器资源已释放');
    }




    getStatus() {
        return {
            isRecording: this.isRecording,
            isInitialized: this.mediaRecorder !== null
        };
    }
}







function blobToFile(blob, filename) {
    return new File([blob], filename, {
        type: blob.type,
        lastModified: Date.now()
    });
}






function playAudioBlob(blob, audioElement) {
    const audioUrl = URL.createObjectURL(blob);
    audioElement.src = audioUrl;
    audioElement.play();
}


window.AudioRecorder = AudioRecorder;
window.blobToFile = blobToFile;
window.playAudioBlob = playAudioBlob;

